package com.mydemo.sftp;

import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;
import lombok.extern.slf4j.Slf4j;

import java.util.Properties;

/**
 * SFTP上传下载工具类
 *
 * @author xiaoming
 */
@Slf4j
public class SftpClient {
    private Session session = null;
    private ChannelSftp channel = null;

    public SftpClient() {
    }

    /**
     * 初始化
     *
     * @param sftpProperty
     * @return
     */
    public SftpClient init(SftpProperty sftpProperty) throws JSchException {
        // 创建JSch对象
        JSch jsch = new JSch();
        // 根据用户名，主机ip，端口获取一个Session对象
        session = jsch.getSession(sftpProperty.getUsername(), sftpProperty.getHost(),
                sftpProperty.getPort());
        if (sftpProperty.getPassword() != null) {
            session.setPassword(sftpProperty.getPassword());
        }
        Properties config = new Properties();
        config.put("userauth.gssapi-with-mic", "no");
        config.put("StrictHostKeyChecking", "no");
        // 为Session对象设置properties
        session.setConfig(config);
        // 设置timeout时间
        session.setTimeout(sftpProperty.getTimeout());
        session.setServerAliveCountMax(sftpProperty.getAliveCountMax());
        session.connect();
        channel = (ChannelSftp) session.openChannel("sftp");
        // 建立SFTP通道的连接
        channel.connect();
        log.info("SSH Channel connected.");
        return this;
    }

    public void disconnect() {
        if (channel != null) {
            channel.disconnect();
        }
        if (session != null) {
            session.disconnect();
            log.info("SSH Channel disconnected.");
        }
    }


    /**
     * 文件上传
     */
    public void upload(String src, String dst) {
        try {
            channel.put(src, dst);
        } catch (Exception e) {
            log.error("", e);
            throw new RuntimeException("发送文件失败！");
        }
    }

    /**
     * @param src 远程文件
     * @param dst 本地文件
     */
    public void get(String src, String dst) {
        try {
            channel.get(src, dst);
        } catch (Exception e) {
            log.error("", e);
            throw new RuntimeException("获取文件失败！");
        }
    }

    /**
     *
     */
    public void reset() {
        try {
            channel.cd(channel.getHome());
            System.out.println(channel.pwd());
        } catch (Exception e) {
            log.error("", e);
            throw new RuntimeException("初始化到根目录！");
        }
    }
}
